/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * RSGeometry.cpp
 *
 *  Created on: 2010/02/16
 *      Author: Alexandre Pires ( c.alexandre.pires@gmail.com )
 */

#include "RSGeometry.h"
#include "RSGeometricElement.h"

namespace Realsphere {

    RSGeometry::RSGeometry ( const QString& rId, const QString& rName ) :
        RSUIDElement ( rId, RS_GEOMETRY_TAG )
    {
        SetName ( rName, false );
        mGeometricElement = NULL;
    }

    RSGeometry::~RSGeometry ()
    {
        mGeometricElement = NULL;
    }

    RSGeometricElement* RSGeometry::GetGeometricElement () const
    {
        return mGeometricElement;
    }

    bool RSGeometry::IsRootElement () const
    {
        return false;
    }

    RSError RSGeometry::SetGeometricElement ( RSGeometricElement* rGeometricElement )
    {
        RSError error = AddChildElement ( rGeometricElement );
        return error;
    }

    RSError RSGeometry::BeforeAddChildElement ( RSElement* rChild )
    {
        RSError error = RSElement::BeforeAddChildElement ( rChild );

        if ( error == RS_INVALID_ELEMENT )
        {
            if ( rChild->InstanceOf ( RS_GEOMETRIC_ELEMENT_CLASS ) )
            {
                error = RS_NO_ERROR;
            }
        }

        return error;
    }

    bool RSGeometry::AfterAddChildElement ( RSElement* rChild )
    {
        bool handled = RSElement::AfterAddChildElement ( rChild );

        if ( !handled && rChild->InstanceOf ( RS_GEOMETRIC_ELEMENT_CLASS ) )
        {
            if ( mGeometricElement != NULL )
                RemoveChildElement ( mGeometricElement );

            mGeometricElement = RSGeometricElementCast ( rChild );
            handled = true;

            emit GeometricElementAdded ( mGeometricElement );
        }

        return handled;
    }

    bool RSGeometry::AfterRemoveChildElement ( RSElement* rChild )
    {
        bool handled = RSElement::AfterRemoveChildElement ( rChild );

        if ( !handled && rChild->InstanceOf ( RS_GEOMETRIC_ELEMENT_CLASS ) )
        {
            RSGeometricElement* geometric_element = RSGeometricElementCast ( rChild );
            mGeometricElement = NULL;
            handled = true;

            emit GeometricElementRemoved ( geometric_element );
        }

        return handled;
    }
}
